package be.kuleuven.peno3.mobiletoledo.view.messages;

import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import be.kuleuven.peno3.mobiletoledo.R;
import be.kuleuven.peno3.mobiletoledo.Data.Client.MessagesClient;
import be.kuleuven.peno3.mobiletoledo.model.Message;

public class List extends Activity {
	private TreeMap<Integer, String> messages;
	private LinearLayout ll;
	
	private int course_id;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try {
			course_id = this.getIntent().getExtras().getInt("course_id");
		} catch (NullPointerException e) {
			course_id=0;
		}
		
		messageCheck();
	}
	
	@Override
	public void onResume() { // Als men een bericht heeft toegevoegd of bekeken, en men keert terug naar deze Activity, moet de lijst met vragen geupdated worden.
		super.onResume();
		messageCheck();
	}
	
	private TreeMap<Integer, String> fetchMessages() {
		Message[] m;
		TreeMap<Integer, String> result = new TreeMap<Integer, String>();
		
		m = MessagesClient.getMessages(course_id); // 0 means fetch messages from all courses

		if(m==null) {
			return null;
		}
		
//		result.put(0, getString(R.string.addanewmessage));
		for(int i=0;i<m.length;i++) {
			result.put(m[i].getId(), m[i].getTitle());
		}
		return result;
	}
	
	private void displayMessages(){
		setContentView(R.layout.textlistlayout);
		
		TextView manQuestBar = (TextView) findViewById(R.id.top_bar);
		manQuestBar.setText("Berichten");
		ll = (LinearLayout) findViewById(R.id.man_quest_ll);
		ll.setPadding(0, 4, 0, 0);
		ll.setGravity(Gravity.CENTER_HORIZONTAL);
		
		Object[] keys = messages.keySet().toArray();
		
		//add a text
		Button button = new Button(this.getApplicationContext());
		button.setText(this.getResources().getString(R.string.addanewmessage));
		button.setTextSize(TypedValue.COMPLEX_UNIT_PT, 10);
		button.setTextColor(0xFF456807);
		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				whenClicked(v);
			}
		});
		ll.addView(button, params);
		
		//add a list of messages
		for(int i=keys.length-1;i>=0;i--){
			int id = (Integer) keys[i];
			
			TextView text = new TextView(this.getApplicationContext());
			ImageView image = new ImageView(this.getApplicationContext());
			if(i == keys.length-1){
				image.setImageDrawable(getResources().getDrawable(R.drawable.line_full));
				image.setPadding(0, 5, 0, 5);
			}
			else{
				image.setImageDrawable(getResources().getDrawable(R.drawable.line));
			}
			ll.addView(image);
			text = new TextView(this.getApplicationContext());
			text.setText(messages.get(id));
			text.setTag(id);
			text.setClickable(true);
			text.setTextSize(TypedValue.COMPLEX_UNIT_PT, 10);
			text.setGravity(Gravity.CENTER_HORIZONTAL);
			text.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					whenClicked(v);
				}
			});
			ll.addView(text);
		}
	}
	
	/**
	 * Called when the user clicks on a menu-item, and opens the correct Activity
	 * @param view The view that was clicked
	 */
	public void whenClicked(View view) {
		TextView v=(TextView) view;
		if(v.getText().equals(getString(R.string.addanewmessage))) {
			Intent i=new Intent(this, Send.class);
			i.putExtra("course_id", course_id);
			startActivity(i);
		}
		else {
			int messageId = (Integer) v.getTag();
			Intent i;
			i = new Intent(this, Show.class);
			i.putExtra("messageId", messageId);
			onClickAnimation(v);
			activityStartDelay(i);
		}
	}
	
	private void messageCheck(){
		messages = fetchMessages();
		if(messages == null){
			Toast.makeText(this.getApplicationContext(), "Er is geen internetverbinding", Toast.LENGTH_SHORT).show();
			finish();
		}
		else if (messages.size() == 0){
			Toast.makeText(this.getApplicationContext(), "Er zijn geen berichten om weer te geven", Toast.LENGTH_SHORT).show();
			displayMessages();
		}
		else {
			displayMessages();
		}
	}
	
	private void onClickAnimation(View view){
		view.startAnimation(AnimationUtils.loadAnimation(this, R.layout.image_click));
	}
	
	private void activityStartDelay(Intent intent){
		int delay = 400; //Time to delay activity startup
		final Intent i = intent;
		final Handler handler = new Handler(); 
        Timer t = new Timer(); 
        t.schedule(new TimerTask() { 
        	public void run() { 
        		handler.post(new Runnable() { 
        			public void run() { 
        				startActivity(i); 
        			} 
        		}); 
        	} 
        }, delay);
	}
}
